package com.wlyuan.open.domain.client.service;

import com.wlyuan.core.domain.valueobj.Mobile;
import com.wlyuan.open.core.exception.OpenClientError;
import com.wlyuan.open.domain.client.OpenClient;
import com.wlyuan.open.domain.client.OpenClientPattern;
import com.wlyuan.open.domain.client.factory.OpenClientFactory;
import com.wlyuan.open.domain.client.respository.OpenClientRepository;
import com.wlyuan.open.dto.api.OpenClientUnbindMobileDTO;
import com.wlyuan.open.remote.facade.User;
import com.wlyuan.open.remote.facade.UserFacade;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author lijing
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OpenClientService {
    private final OpenClientRepository openClientRepository;
    private final UserFacade userFacade;
    private final OpenClientFactory openClientFactory;


    public OpenClient unbindMobile(OpenClient application, OpenClientUnbindMobileDTO unbind) {
        Mobile mobile = new Mobile(unbind.getMobile());
        var pattern = new OpenClientPattern(mobile.getValue(), "");
        var applicationClient = openClientRepository.ofPatternMobile(pattern);
        if (null != applicationClient) {
            throw new OpenClientError("手机号已存在");
        }
        application.changeMobile(mobile);
        openClientRepository.save(application);
        //绑定了企业版账号则，修改绑定账号
        if (application.bind()) {
            userFacade.bindAccount(application.getUserId().getId(), mobile.getValue());
        }
        return application;
    }

    public OpenClient changeAppSecret(OpenClient application) {
        if (!application.bind()) {
            throw new OpenClientError("需要绑定企业版管理员账号后才能重置");
        }
        return openClientFactory.changeAppSecret(application);
    }

    public OpenClient bind(OpenClient application, User user, OpenClient afterApplication) {
        //绑定的租户id是否已经存在,已经绑定过的原账号需要释放
        Optional.ofNullable(afterApplication).ifPresent(c -> {
            c.unbind();
            openClientRepository.save(c);
        });
        //解绑原管理员账号绑定账号信息
        if (application.bind()) {
            userFacade.unBindAccount(application.getUserId().getId());
        }
        application.bind(user.getTenantId(), user.getUserId(), user.getName());
        openClientRepository.save(application);
        //绑定企业版账号
        userFacade.bindAccount(application.getUserId().getId(), application.getMobile());
        return application;
    }

    public OpenClient ofAppId(String appId) {
        return openClientRepository.ofAppId(appId);
    }
}
